﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using CommunergyLogic;
using System.Data.Linq;
using Communergy.NationalGridDataServices;
using AzureLibrary;
using Communergy.Repository;

namespace CarbonIntensityReader
{
    public class WorkerRole : RoleEntryPoint
    {
        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.WriteLine("CarbonIntensityReader entry point called", "Information");

            while (true)
            {
                DateTime dateTimeNextRead;
                //TODO - from config
                string url = "http://www.realtimecarbon.org/ws/electricity/services/co2profile/5minute/item";

                var currentCarbonIntensityXml = GridDataHelper.GetRemoteXml(url);
                Trace.WriteLine(string.Format("Received data: {0}", currentCarbonIntensityXml), "Information");
                var liveCarbonIntensityData = GridDataHelper.LiveCarbonIntensityFromXml(currentCarbonIntensityXml);
                var liveCarbonIntensity = NationalGridDataHelper.CreateLiveCarbonIntensity(liveCarbonIntensityData);
                if (liveCarbonIntensity != null)
                {
                    communergyEntities db = new communergyEntities(ConfigurationHelper.EntityFrameworkConnectionString);
                    db.AddToLiveCarbonIntensity(liveCarbonIntensity);
                    Trace.WriteLine(string.Format("Saving intensity data: {0}", liveCarbonIntensity.lc_carbonIntensity));
                    db.SaveChanges();

                    dateTimeNextRead = liveCarbonIntensity.lc_startDateTime.Value.AddMinutes(7);
                }
                else
                {
                    dateTimeNextRead = DateTime.Now.AddMinutes(2);
                }
                var timeBeforeNextRead = dateTimeNextRead.Subtract(DateTime.Now);


                Thread.Sleep((int)timeBeforeNextRead.TotalMilliseconds);
            }
        }

        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 12;

            DiagnosticMonitor.Start("DiagnosticsConnectionString");

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
            RoleEnvironment.Changing += RoleEnvironmentChanging;

            return base.OnStart();
        }

        private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)
        {
            // If a configuration setting is changing
            if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))
            {
                // Set e.Cancel to true to restart this role instance
                e.Cancel = true;
            }
        }
    }
}
